package com.xxg.fileshand.base

import android.os.Bundle
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import android.widget.LinearLayout
import android.widget.TextView
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.LogUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.dylanc.viewbinding.inflateBindingWithGeneric
import com.gyf.immersionbar.ImmersionBar
import com.lxj.xpopup.XPopup
import com.rscja.barcode.BarcodeDecoder
import com.rscja.barcode.BarcodeFactory
import com.rscja.barcode.BarcodeUtility
import com.rscja.deviceapi.entity.UHFTAGInfo
import com.xxg.fileshand.R
import com.xxg.fileshand.activity.GoodsInventoryActivity
import com.xxg.fileshand.adapter.FilesAdapter
import com.xxg.fileshand.app.SetInfo
import com.xxg.fileshand.base.ext.getApiService
import com.xxg.fileshand.greendao.FilesInfoDTO
import com.xxg.fileshand.greendao.WzInfoDTO
import com.xxg.fileshand.net.NetWorkException
import com.xxg.fileshand.reader.ReaderUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import retrofit2.HttpException
import java.io.IOException
import java.lang.ref.WeakReference

abstract class BaseVMActivity<V : ViewBinding, VM : BaseViewModel> :
    BaseActivity() {

    lateinit var mBinding: V

    protected lateinit var mViewModel: VM

    lateinit var filesAdapter: FilesAdapter

    var filesList: MutableList<FilesInfoDTO> = mutableListOf()

    var isScanTMCode = false//扫条码模式

    var barcodeDecoder = BarcodeFactory.getInstance().barcodeDecoder


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)

        mBinding = inflateBindingWithGeneric(layoutInflater)
        setContentView(mBinding.root)

        initViewModel()

        ImmersionBar.with(this)
            .statusBarDarkFont(true)
            .fitsSystemWindows(false).init()

        findViewById<TextView>(R.id.tv_title)?.text = getMyTitle()
        showLeftText()
        if (isScan() && !isFinishing) {
            ReaderUtils.instance.callBack = WeakReference(callBack)
            ReaderUtils.instance.isScanningRFID.observe(this) {
                if (it) {
                    findViewById<LinearLayout>(R.id.ll_root_scan)?.background =
                        getDrawable(R.mipmap.bg_base_red)
                } else {
                    findViewById<LinearLayout>(R.id.ll_root_scan)?.background =
                        getDrawable(R.mipmap.bg_base)
                }
            }

            launch({
                withContext(Dispatchers.IO) {
                    if (barcodeDecoder.open(this@BaseVMActivity)) {
                        BarcodeUtility.getInstance()
                            .enablePlaySuccessSound(this@BaseVMActivity, true);
                        barcodeDecoder.setDecodeCallback { barcodeEntity ->
                            if (barcodeEntity.resultCode == BarcodeDecoder.DECODE_SUCCESS) {
                                onTmCodeRead(barcodeEntity.barcodeData)
                            }
                        }
                    } else {
                        LogUtils.e("条码模块打开失败")
                    }
                }
            })
        }
    }

    private val callBack = object : ReaderUtils.CallBack {
        override fun readEpc(tagInfo: UHFTAGInfo) {
            runOnUiThread {
                LogUtils.e("读取到的标签：${tagInfo.epc}")
                onEpcRead(tagInfo)
            }
        }

        override fun returnPower(power: Int) {
        }

        override fun setPowerSuccess(power: Int) {
            LogUtils.e("设置功率成功：$power")
        }
    }

    open fun getMyTitle(): String {
        return "标题"
    }

    open fun isScan(): Boolean {
        return false
    }

    open fun showRightText(text: String) {
        findViewById<TextView>(R.id.tv_right)?.let {
            it.text = text
            it.visibility = View.VISIBLE
            it.setOnClickListener {
                onRightClick()
            }
        }
    }

    open fun onRightClick() {
    }

    open fun showLeftText(text: String = "返回") {
        findViewById<TextView>(R.id.tv_left)?.let {
            it.text = text
            it.visibility = View.VISIBLE
            it.setOnClickListener {
                onLeftClick()
            }
        }
    }

    open fun onLeftClick() {
    }

    open fun initFilesAdapter() {
        filesAdapter = FilesAdapter()
        findViewById<RecyclerView>(R.id.rv_files)?.adapter = filesAdapter
        filesAdapter.setNewInstance(filesList)

        //判断是否是GoodsInventoryActivity
        if (ActivityUtils.getTopActivity() !is GoodsInventoryActivity) {
            filesAdapter.setOnItemLongClickListener() { adapter, view, position ->
                XPopup.Builder(this)
                    .asConfirm("提示", "是否删除该档案？") {
                        ReaderUtils.instance.removeTid(filesList[position].eid)
                        filesList.removeAt(position)
                        filesAdapter.notifyItemRemoved(position + filesAdapter.headerLayoutCount)
                        listChange()
                    }.show()
                true
            }
        }


    }

    fun initAdapterClick(hintView: View? = null) {
        filesAdapter.addChildClickViewIds(R.id.bt_open_jia, R.id.bt_close_jia)
        filesAdapter.setOnItemChildClickListener(object : OnItemChildClickListener {
            override fun onItemChildClick(
                adapter: BaseQuickAdapter<*, *>,
                view: View,
                position: Int
            ) {
                if (view.id == R.id.bt_open_jia || view.id == R.id.bt_close_jia) {
                    if (!SetInfo.isOffline()) {
                        launch({
                            val rp = getApiService().shelvingAction(
                                mapOf(
                                    "action" to if (view.id == R.id.bt_open_jia) 100 else 101,
                                    "caseCode" to filesAdapter.data[position].caseCode,
                                    "daCode" to filesAdapter.data[position].daCode,
                                    "daName" to filesAdapter.data[position].daName,
                                )
                            )
                            toast("操作成功")
                        })
                    }
                } else if (view.id == R.id.bt_find) {
                    hintView?.visibility = View.GONE
                    ReaderUtils.instance.needReadTid = filesAdapter.data[position].eid
                    toRead()
                }
            }
        })

    }

    open fun listChange() {
    }

    /**
     * 初始化ViewModel
     */
    private fun initViewModel() {
        val viewModelClass: Class<VM>? = ClassUtil.getViewModel(this)
        if (viewModelClass != null) {
            mViewModel = ViewModelProvider(this)[viewModelClass]
        }
    }

    fun showException(e: Throwable) {
        var code = 0
        var errorMsg = e.message
        if (e is Exception) {
            if (e is IOException) {
                /** 没有网络  */
                errorMsg = "Please check your network status"
            } else if (e is HttpException) {
                /** 网络异常，http 请求失败，即 http 状态码不在 [200, 300) 之间, such as: "server internal error".  */
//            errorMsg = ((HttpException) e).response().message();
                e.response()?.apply {
                    code = code()
                    if (errorBody() != null) {
                        errorMsg = errorBody()!!.string()
                    }
                }
            } else if (e is NetWorkException) {
                code = e.code
                errorMsg = e.message
            } else {
                /** 其他未知错误  */
                errorMsg = if (!TextUtils.isEmpty(e.message)) e.message else "unknown error"
            }
            if (errorMsg == "") {
                errorMsg = e.message
            }
            toast(errorMsg)
//            loadFailure(code, errorMsg!!)
            e.printStackTrace()
        }
    }

    override fun finish() {
        hideSoftKeyboard()
        super.finish()
    }

    open fun toRead() {
        if (ReaderUtils.instance.isInit != true) {
            toast("设备还未初始化")
        } else if (ReaderUtils.instance.isScanningRFID.value == true) {
            ReaderUtils.instance.stopScan()
        } else if (ReaderUtils.instance.isScanningRFID.value == false) {
            ReaderUtils.instance.startScan()
        }
    }

    override fun onBackPressed() {
        super.onBackPressed()
        ReaderUtils.instance.callBack = null
        ReaderUtils.instance.reset()
    }

    open fun onEpcRead(tagInfo: UHFTAGInfo) {
    }

    open fun onTmCodeRead(code: String) {

    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (isScan() && !isFinishing) {
            if (ReaderUtils.instance.isScanBtn(keyCode) && event?.repeatCount == 0) {
                if (!isScanTMCode) {
                    toRead()
                } else {
                    if (barcodeDecoder.isOpen) {
                        if (!barcodeDecoder.startScan()) {
                            toast("扫码开启失败")
                        }
                    } else {
                        toast("扫码功能还未初始化")
                    }
                }
            }
        }
        return super.onKeyDown(keyCode, event)
    }
}